package com.wkbb.basic.smartschool;

import com.alibaba.fastjson.JSON;
import com.google.common.reflect.TypeToken;
import com.wkbb.basic.smartschool.bean.*;
import com.wkbb.common.utils.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yxl 2019-4-11
 * 智慧校园HttpClient工具类
 */
public class SSHttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(SSHttpClientUtil.class);

    private static final String PAGE_SIZE = "100";

    /**
     * 发送消息格式
     */
    private static final String MSG_TYPE_TEXT = "text";
    private static final String MSG_TYPE_IMAGE = "image";
    private static final String MSG_TYPE_TEXT_CARD = "textcard";
    private static final String MSG_TYPE_NEWS = "news";
    /**
     * 智慧校园API地址
     */
    private static final String SS_SERVER = "https://open.campus.qq.com/api/";
    /**
     * 获取学校信息
     */
    private static final String GET_OBJ_INFO = SS_SERVER + "open/getObjectInfo";
    /**
     * 获取组织架构列表
     */
    private static final String GET_DEPART_LIST = SS_SERVER + "open/getDepartmentInfoList";
    /**
     * 获取组织架构信息
     */
    private static final String GET_DEPART_INFO = SS_SERVER + "open/getDepartInfoById";

    /**
     * 获取用户列表
     */
    private static final String SEARCH_USER = SS_SERVER + "common/searchUser";
    /**
     * 获取家长列表
     */
    private static final String GET_PARENT_LIST = SS_SERVER + "userInfo/parentList";
    /**
     * 获取用户详情
     */
    private static final String GET_USER_INFO = SS_SERVER + "open/getUserInfo";
    /**
     * 获取用户人脸
     */
    private static final String GET_USER_FACE = SS_SERVER + "open/GetUserFaceImage";
    /**
     * 获取学生-家长关系
     */
    private static final String GET_STU_FAM = SS_SERVER + "open/getParentRelation";
    /**
     * 获取近期用户更新列表
     */
    private static final String GET_UPDATE_USER = SS_SERVER + "open/getUpdateUser";
    /**
     * 获取近期学生-家长更新列表
     */
    private static final String GET_UPDATE_STU_FAM = SS_SERVER + "open/getUpdateParentRelation";
    /**
     * 消息推送
     */
    private static final String SEND_MESSAGE = SS_SERVER + "open/sendMsg";

    /**
     * 返回错误码
     */
    public static final Integer CODE=0;


    public static String getObjectInfo(String objId) {
        return SSHttpClientUtil.doGet(GET_OBJ_INFO, null, objId);
    }

    public static WitCampusResult<List<DepartInfoDto>> getDepartList(String objId, String userType) {
        HashMap<String, String> params = new HashMap<>();
        params.put("usertype", userType);
        String reslut = SSHttpClientUtil.doGet(GET_DEPART_LIST, params, objId);
        Type type = new TypeToken<WitCampusResult<List<DepartInfoDto>>>() {
        }.getType();
        return JSON.parseObject(reslut, type);
    }


    public static WitCampusResult<List<DepartInfoDto>> getDepartInfo(String objId, String departid) {
        HashMap<String, String> params = new HashMap<>();
        params.put("departid", departid);
        String reslut = SSHttpClientUtil.doGet(GET_DEPART_INFO, params, objId);
        Type type = new TypeToken<WitCampusResult<List<DepartInfoDto>>>() {
        }.getType();
        return JSON.parseObject(reslut, type);
    }

    public static WitCampusResult<UserListBean> searchUser(String objId, String userType, String departId, String level, String key, String page, String pageSize) {
        HashMap<String, String> params = new HashMap<>();
        params.put("usertype", userType);
        params.put("departid", departId);
        params.put("level", level);
        if (key != null) {
                params.put("key", key);
        }
        if(page!=null){
            params.put("page", page);
        }
        if(pageSize!=null){
            params.put("pageSize", pageSize);
        }
        String result = SSHttpClientUtil.doGet(SEARCH_USER, params, objId);
        Type type = new TypeToken<WitCampusResult<UserListBean>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<UserListBean> getParentList(String objId, String departId, String level, String key, String page, String pageSize) {
        HashMap<String, String> params = new HashMap<>();
        params.put("departid", departId);
        params.put("level", level);
        if (key != null) {
            params.put("key", key);
        }
        params.put("page", page);
        params.put("pageSize", StringUtil.isEmpty(pageSize) ? PAGE_SIZE : page);
        String result = SSHttpClientUtil.doGet(GET_PARENT_LIST, params, objId);

        Type type = new TypeToken<WitCampusResult<UserListBean>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<SSUserInfoDto> getUserInfo(String objId, String userId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", userId);
        String result = SSHttpClientUtil.doGet(GET_USER_INFO, params, objId);

        Type type = new TypeToken<WitCampusResult<SSUserInfoDto>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<List<SSFaceInfoBean>> getUserFace(String objId, String users, String key, String keyId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("users", users);
        String result = SSHttpClientUtil.doGet(GET_USER_FACE, params, objId, key, keyId);
        Type type = new TypeToken<WitCampusResult<List<SSFaceInfoBean>>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<List<StuFamBean>> getStuFam(String objId, String userId) {
        return getStuFam(objId, userId, "1");
    }

    /**
     * 获取学生家长信息
     *
     * @param objId    学校ID
     * @param userId   用户ID
     * @param userType 角色类型（1-学生；3-家长 )
     * @return 学生家长信息
     */
    public static WitCampusResult<List<StuFamBean>> getStuFam(String objId, String userId, String userType) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", userId);
        params.put("usertype", userType);
        String result = SSHttpClientUtil.doGet(GET_STU_FAM, params, objId);

        Type type = new TypeToken<WitCampusResult<List<StuFamBean>>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<UpdateListBean> getUpdateUser(String objId, String dayNum) {
        HashMap<String, String> params = new HashMap<>();
        params.put("dayNum", dayNum);
        String result = SSHttpClientUtil.doGet(GET_UPDATE_USER, params, objId);

        Type type = new TypeToken<WitCampusResult<UpdateListBean>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult<UpdateListBean> getUpdateStuFam(String objId, String dayNum) {
        HashMap<String, String> params = new HashMap<>();
        params.put("dayNum", dayNum);
        String result = SSHttpClientUtil.doGet(GET_UPDATE_STU_FAM, params, objId);
        Type type = new TypeToken<WitCampusResult<UpdateListBean>>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    public static WitCampusResult sendMessage(String objId, String wxUserId,
                                              String title, String description, String url, String picurl) {
        return sendMessage(objId, wxUserId, null, title, description, url, picurl);
    }

    public static WitCampusResult sendMessage(String objId, String wxUserId, String wxDepartId,
                                              String title, String description, String url, String picurl) {
        return sendMessage(objId, "textcard", wxUserId, wxDepartId, title, description, url, picurl);
    }


    public static WitCampusResult sendMessage(String objId, String msgType, String wxUserId, String wxDepartId,
                                              String title, String description, String url, String picurl) {
        HashMap<String, String> params = new HashMap<>();
        params.put("data[msgtype]", msgType == null ? "text" : msgType);
        if (wxUserId != null) {
            params.put("data[wxuserid]", wxUserId);
        }
        if (wxDepartId != null) {
            params.put("data[wxdepartid]", wxDepartId);
        }
        if (msgType == null || MSG_TYPE_TEXT.equals(msgType) || MSG_TYPE_IMAGE.equals(msgType)) {
            params.put("data[content]", title);
        } else {
            params.put("data[content][title]", title);
            params.put("data[content][description]", description == null ? "" : description.replace("\\n", "\n"));
            params.put("data[content][url]", url == null ? "" : url);
            params.put("data[content][picurl]", picurl == null ? "" : picurl);
        }
        String result = SSHttpClientUtil.doPost(SEND_MESSAGE, params, objId);

        Type type = new TypeToken<WitCampusResult>() {
        }.getType();
        return JSON.parseObject(result, type);
    }

    private static String doPost(String url, Map<String, String> param, String objId, String key, String keyId) {
        if (param == null) {
            param = new HashMap<>();
        }
        SSSignUtil.putSignStr(param, objId, key, keyId);
        return doPost(url, param);
    }

    private static String doPost(String url, Map<String, String> param, String objId) {
        if (param == null) {
            param = new HashMap<>();
        }
        // 加入鉴权参数
        SSSignUtil.putSignStr(param, objId);
        return doPost(url, param);
    }

    private static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();

                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
                logger.info("paramList******************is" + paramList);
            }
            // 执行http请求
            logger.info("httpPost******************is" + httpPost);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            logger.error("智慧校园http请求异常", e);
            return String.valueOf("请求失败，请再次尝试");
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    private static String doGet(String url, Map<String, String> param, String objId, String key, String keyId) {
        if (param == null) {
            param = new HashMap<>();
        }
        SSSignUtil.putSignStr(param, objId, key, keyId);
        return doGet(url, param);
    }

    private static String doGet(String url, Map<String, String> param, String objId) {
        if (param == null) {
            param = new HashMap<>();
        }
        // 加入鉴权参数
        SSSignUtil.putSignStr(param, objId);
        return doGet(url, param);
    }

    private static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString;
        try {
            // 创建Http Post请求
            HttpGet httpGet = new HttpGet(url);
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            httpGet.setURI(uri);
            // 执行http请求
            response = httpClient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            logger.error("智慧校园http请求异常", e);
            return String.valueOf("请求失败，请再次尝试");
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

}
